<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  
  <link rel="stylesheet" href="/public/asset/bootstrap.min.css">
  <link rel="stylesheet" href="/public/asset/bootstrap-icons-141.css">
  <link rel="stylesheet" href="/public/asset/style.css">
  
  <script src="/public/asset/jquery.min.js"></script>
  <script src="/public/asset/dayjs.min.js"></script>
  <script src="/public/asset/bootstrap.bundle.min.js"></script>
  <script src="/public/asset/util.js"></script>
  <script src="/public/asset/my-messages.js"></script>
  
  <title>My Messages - iPelago</title>
  <style>
    .bi {
      cursor: pointer;
    }
    .bi-trash {
      color: #ccc;
    }
    .bi-trash:hover {
      color: red;
    }
  </style>
</head>
<body>
  <div id="root" class="container" style="max-width: 775px; min-width: 400px;"></div>

<script>

let myAvatar;
let lastTime;

const Loading = CreateLoading();
const Alerts = CreateAlerts();

const PublishBtn = cc('button');
const TitleArea = {
  view: () => m('div').addClass('d-flex justify-content-start align-items-end my-5').append([
    m('div').addClass('display-6').text('My Messages'),
    m(PublishBtn).text('publish').attr({type:'button'})
      .addClass('btn btn-outline-success btn-sm ms-2').hide(),
    m('a').attr({href:'/public/home.html',title:'home'})
      .addClass('btn btn-outline-secondary btn-sm ms-2').append(
        m('i').addClass('bi bi-house-door')
    ),
  ]),
};

const MsgList = cc('ul');

MsgList.view = () => m('ul')
  .attr({id:MsgList.raw_id}).addClass('list-group list-group-flush');

MsgList.append = (messages) => {
  messages.forEach((msg) => {
    const item = MsgItem(msg);
    $(MsgList.id).append(m(item));
  });
};

const MoreBtn = cc('button');
const SubmitAlerts = CreateAlerts();

const SubmitBtnArea = cc('p', null, [
  m(MoreBtn).text('More').addClass('btn btn-primary').attr({type:'button'}).hide(),
]);

$('#root').append([
  m(TitleArea),
  m(Loading),
  m(MsgPostArea).hide(),
  m(Alerts).addClass('my-3'),
  m(MsgList),
  m(SubmitAlerts),
  m(SubmitBtnArea).addClass('text-center my-5'),
]);

init();

async function init() {
  await initMyAvatar();
  ajax({method:'GET',url:'/api/more-my-messages',alerts:Alerts},
      (messages) => {
        if (!messages || messages.length == 0) {
          Alerts.insert('info', '没有任何消息，可能尚未建岛');
          return;
        }
        if (messages.length > 10) {
          $(MoreBtn.id).show();
        }
        $(PublishBtn.id).show();
        $(MsgPostArea.id).show();
        window.setTimeout(() => { $(MsgInput.id).focus(); }, 500);
        MsgList.append(messages);
        lastTime = messages[messages.length-1].Time;

        if (messages.length >= everyPage) {
          $(MoreBtn.id).show().click(() => {
            ajax({method:'GET',url:'/api/more-my-messages?time='+lastTime,alerts:SubmitAlerts,buttonID:MoreBtn.id},
                (moreMessages) => {
                  if (!moreMessages || moreMessages.length == 0) {
                    SubmitAlerts.insert('primary', '没有更多消息了');
                    $(MoreBtn.id).hide();
                    return;
                  }
                  MsgList.append(moreMessages);
                  lastTime = moreMessages[moreMessages.length-1].Time;
                });
          });
        }
        $(PublishBtn.id).click(() => {
          ajax({method:'GET',url:'/api/publish-newsletter',alerts:SubmitAlerts,buttonID:PublishBtn.id},
              () => {
                window.location = '/public/publish.html';
              });
        });
      }, null, () => {
        $(Loading.id).hide();
      });
}

function itemID(id) {
  return `i${id}`;
}

function MsgItem(msg) {
  let contentsElem;
  const httpLink = msg.Body.match(httpRegex);
  if (!httpLink) {
    contentsElem = msg.Body;
  } else {
    contentsElem = [
      msg.Body.substring(0, httpLink.index),
      m('a').text(httpLink[0]).attr({href:httpLink[0],target:'_blank'}),
      msg.Body.substring(httpLink.index + httpLink[0].length),
    ];
  }
  const datetime = dayjs.unix(msg.Time).format('YYYY-MM-DD HH:mm:ss');
  const ItemAlerts = CreateAlerts();
  const self = cc('div', itemID(msg.ID))

  self.view = () => m('li').attr({id:self.raw_id}).addClass('list-group-item d-flex justify-content-start align-items-start MsgItem mb-3').append([
    m('img').addClass('Avatar').attr({src:myAvatar}),
    m('div').addClass('ms-3 flex-fill').append([
      m('div').addClass('Datetime small text-muted').append([
        m('span').text(datetime),
        m('span').text('DELETED').addClass('Deleted badge bg-secondary ms-1').hide(),
        m('i').addClass('bi bi-trash ms-1').attr({title:'delete'}).click(() => {
          const body = new FormData();
          body.set('id', msg.ID);
          ajax({method:'POST',url:'/api/delete-message',alerts:ItemAlerts,buttonID:`${self.id} .bi-trash`,body:body},
              () => {
                $(self.id).find('.Contents').addClass('text-muted');
                $(`${self.id} a`).removeAttr('href');
                $(self.id).find('.Deleted').toggle();
                $(self.id).find('.bi-trash').toggle();
                $(self.id).find('.Avatar').css('filter', 'opacity(0.5) grayscale(1)');
              });
        }),
      ]),
      m('div').addClass('Contents').append(contentsElem),
      m(ItemAlerts),
    ]),
  ]);

  // 接口要求有 init 函数。
  self.init = () => {};

  return self;
}

function initMyAvatar() {
  return new Promise(resolve => {
    ajax({method:'GET',url:'/api/get-island/My-Island-ID',alerts:Alerts},
      (island) => {
        myAvatar = island.Avatar ? island.Avatar : '/public/avatars/default.jpg';
        resolve();
      });
  })
}

</script>
</body>
</html>